"use strict";
const mvc = require('cosjs.mvc');
const random = mvc.library.require('random');
/**
 * @name star
 * 流星
 */

/**
 * @name getStar
 * 获取流星数据
 */
exports.getStar = async function () {
    //获取star信息
    this.updater.role.key('star');
    // this.updater.role.key('stage.normal');
    this.updater.role.key('battlePoint');
    // this.updater.role.key('starList');
    // this.updater.role.key('lastHangStage');
    await this.updater.data();
    let battlePoint = this.updater.role.get('battlePoint') || 0;
    let star = this.updater.role.get('star');
    // let starList = this.updater.role.get('starList')||[];
    let nowtime = this.updater.time;
    const maxStarConfig = mvc.config('base', 'meteorMaxNum')
    const useTimeConfig = mvc.config('base', 'meteorRefreshTime')
    let maxStar = maxStarConfig.val;
    //DEBUG:TypeError: Cannot read property 'length' of undefined
    if (star.starList.length >= maxStar) {
        star.lastGetTime = nowtime;
        this.updater.role.set("star.lastGetTime", nowtime);
    } else if (nowtime > star.lastGetTime) {
        let subTime = nowtime - star.lastGetTime;
        let useTime = useTimeConfig.val * 1000;
        // console.log("now time:", nowtime);
        // console.log("star.lastGetTime:", star.lastGetTime);
        // console.log("subtime:", subTime);
        // console.log("useTime:", useTime);
        let num = parseInt(subTime / useTime);
        // console.log("num:", num);
        let starMap = [];
        let allPoint = 0;
        //从表里读流星的概率
        let starConfig = this.config("meteorGroup");
        if (!starConfig) {
            return this.quick_error("M7GHLB123", 'config_not_exist', "meteorGroup");
        }
        // let lastStage = this.updater.role.get('stage.normal');
        let starNum = 0;
        for (let i in starConfig) {
            //判断是否解锁此流星，感觉是bug啊，这样1-1到1-3就不刷流星了诶
            if (battlePoint >= starConfig[i].effectStage) {
                starMap.push({ "ID": starConfig[i].meteorID, "val": starConfig[i].val })
                allPoint += starConfig[i].val;
                starNum++;
            }
        }
        if (starNum == 0) {
            return star;//this.quick_error("M7GHLB123", 'err request', lastStage);
        }
        //补到上限5
        for (let i = 0; i < num; i++) {
            if (star.starList.length >= maxStar) {
                break;
            }
            let k = random.Relative(starMap, 'val');
            if (k === false) {
                return this.quick_error("M7GHLB123", 'err request', k);
            }
            star.lastGetTime = nowtime;
            star.starList.push(parseInt(starMap[k].ID, 10));
        }
        this.updater.role.set('star', star);
    }
    await this.updater.save();
    return star;
}



/**
 * @name useStar
 * @param int starID 流星ID
 * 使用流星
 */
exports.useStar = async function () {
    //获取star信息
    let starID = this.get('starID', 'int');
    if (!starID) {
        return this.quick_error("M2saghge10", "参数缺失starID");
    }
    this.updater.role.key('star');
    this.updater.role.key('starBuff');
    await this.updater.data();
    let star = this.updater.role.get('star');
    let starBuff = this.updater.role.get('starBuff');
    let nowtime = this.updater.time;
    // let flag = 0;
    for (let i = 0; i < star.starList.length; i++) {
        if (starID == star.starList[i]) {
            //符合条件
            //区分流星类型
            const starConfig = this.config("meteorEffect", star.starList[i]);
            if (!starConfig) {
                return this.quick_error("M7GHLB123", 'config_not_exist', "meteorEffect", star.starList[i]);
            }
            const starBuffConfig = this.config("starBuff", starConfig.buffGroup);
            if (!starBuffConfig) {
                return this.quick_error("M7GHLB123", 'config_not_exist', "meteorEffect", starConfig.buffGroup);
            }
            for (let j = 0; j < starBuffConfig.Coll.length; j++) {
                switch (starBuffConfig.Coll[j].buffEffect) {
                    case 'item':
                        //给物品
                        let randNum = Math.roll(starBuffConfig.Coll[j].randomMin, starBuffConfig.Coll[j].randomMax);
                        this.updater.add(parseInt(starBuffConfig.Coll[j].val), randNum);
                        // flag = 1;
                        break;
                    case 'buff':
                        //添加buff
                        let buffData = {
                            "val": starBuffConfig.Coll[j].val,
                            "ifPercent": starBuffConfig.Coll[j].ifPercent,
                            "field": starBuffConfig.Coll[j].field,
                            "randomVal": Math.roll(starBuffConfig.Coll[j].randomMin, starBuffConfig.Coll[j].randomMax),
                            "beginTime": nowtime,
                            "endTime": nowtime + Math.roll(starBuffConfig.Coll[j].timeMin, starBuffConfig.Coll[j].timeMax) * 1000
                        }
                        starBuff.buff.push(buffData);
                        // flag = 2;
                        break;
                    case 'itembuff':
                        //添加buff
                        let itemBuffData = {
                            "val": starBuffConfig.Coll[j].val,
                            "ifPercent": starBuffConfig.Coll[j].ifPercent,
                            "randomVal": Math.roll(starBuffConfig.Coll[j].randomMin, starBuffConfig.Coll[j].randomMax),
                            "beginTime": nowtime,
                            "endTime": nowtime + Math.roll(starBuffConfig.Coll[j].timeMin, starBuffConfig.Coll[j].timeMax) * 1000
                        }
                        starBuff.itemBuff.push(itemBuffData);
                        // flag = 3;
                        break;
                    case 'monster':
                        //给怪物
                        let waveConfig = this.config("wave", starBuffConfig.Coll[j].val);
                        if (!waveConfig) {
                            return this.quick_error("m2sgrbs1", "wave配置不存在", starBuffConfig.Coll[j].val);
                        }
                        for (let i = 0; i <= waveConfig.Coll.length; i++) {
                            let Coll = waveConfig.Coll[i]
                            if (Coll == undefined) {
                                continue;
                            }
                            for (let j = 0; j < Coll.number; j++) {
                                let reward = [];
                                if (Coll.box) {
                                    let { err, ret } = this.library("item/group", Coll.box, 1); //this.updater.item.group(Coll.box);
                                    if (err) {
                                        return this.error(err, ret);
                                    }
                                    reward = reward.concat(ret);
                                    // reward.push(ret);
                                }
                                if (Coll.starReward) {
                                    reward.push({ "id": 60100002, "num": Coll.starReward, "key": reward.length });
                                }
                                if (Coll.expReward) {
                                    reward.push({ "id": 60100001, "num": Coll.expReward, "key": reward.length })
                                }
                                let waveData = { "waveID": Coll.waveID, "mid": Coll.waveKey, "reward": reward };
                                starBuff.monster.push(waveData);
                            }
                        }
                        // flag = 4;
                        break;
                    default:
                        return this.quick_error("M7GHLB123", 'config_not_exist', "meteorEffect", starBuffConfig.Coll[j].meteorType);
                }
            }
            star.starList.splice(i, 1);
            i--;
            break;
        }
    }
    this.updater.role.set('star', star);
    for (let i = 0; i < starBuff.buff.length; i++) {
        if (starBuff.buff[i].endTime < nowtime) {
            starBuff.buff.splice(i, 1);
            i--;
        }
    }
    for (let i = 0; i < starBuff.itemBuff.length; i++) {
        if (starBuff.itemBuff[i].endTime < nowtime) {
            starBuff.itemBuff.splice(i, 1);
            i--;
        }
    }
    this.updater.role.set('starBuff', starBuff);
    this.updater.record.add("71", 1);
    this.updater.daily.add("record.71", 1);
    await this.updater.save();
    return;
}




/**
 * @name killStarMonster
 * @param int waveID 波叔ID
 * @param int monsterID 怪物ID
 * 杀死流星怪物
 */
exports.killStarMonster = async function () {
    let waveID = this.get('waveID', 'int');
    if (!waveID) {
        return this.quick_error("M2saghge10", "参数缺失monsterID");
    }
    let monsterID = this.get('monsterID', 'int');
    if (!monsterID) {
        return this.quick_error("M2saghge10", "参数缺失monsterID");
    }
    this.updater.role.key('starBuff.monster');
    await this.updater.data();
    let monsterList = this.updater.role.get('starBuff.monster');
    // let flag = 0;
    for (let i = 0; i < monsterList.length; i++) {
        if (monsterList[i].mid == monsterID && monsterList[i].waveID == waveID) {
            for (let j = 0; j < monsterList[i].reward.length; j++) {
                this.updater.item.add(monsterList[i].reward[j].id, monsterList[i].reward[j].num);
            }
            monsterList.splice(i, 1);
            i--;
            break;
        }
    }
    this.updater.role.set('starBuff.monster', monsterList);
    await this.updater.save();
    return;
}




/**
 * @name clearMonster
 * 清空流星怪物
 */
exports.clearMonster = async function () {
    this.updater.role.set('starBuff.monster', []);
    await this.updater.save();
    return;
}